package com.cssw.fyzb.busi.service.task;

import com.alibaba.fastjson.JSON;
import com.cssw.fyzb.busi.config.EventClient;
import com.cssw.fyzb.busi.util.Const;
import com.cssw.fyzb.busi.util.UuidUtil;
import com.cssw.fyzb.core.dao.acct.AcctDao;
import com.cssw.fyzb.core.dao.adnumprice.AdNumPriceDao;
import com.cssw.fyzb.core.dao.team.UserTreeDao;
import com.cssw.fyzb.core.dao.tesk.*;
import com.cssw.fyzb.core.dao.turntable.TurntableNumPriceDao;
import com.cssw.fyzb.core.dao.user.UserDao;
import com.cssw.fyzb.core.dao.video.TaskViewAdvertDao;
import com.cssw.fyzb.core.eao.acct.AcctLogEao;
import com.cssw.fyzb.core.mao.task.DailyTaskMao;
import com.cssw.fyzb.core.mao.task.TaskStatMao;
import com.cssw.fyzb.core.mao.video.VideoViewStatMao;
import com.cssw.fyzb.core.model.dodb.*;
import com.cssw.fyzb.core.model.mos.DailyTaskMo;
import com.cssw.fyzb.core.model.mos.TaskStatMo;
import com.cssw.fyzb.core.model.mos.VideoViewStatMo;
import com.cssw.fyzb.core.model.vo.task.CollecTaskVo;
import com.cssw.fyzb.core.model.vo.task.OnDayTaskVo;
import com.cssw.fyzb.core.util.*;
import com.ydn.dbframe.plugin.activerecord.Db;
import com.ydn.dbframe.plugin.activerecord.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.cssw.fyzb.core.util.Bizs.ERROR_ACCT_DATA_CHANGE;

/**
 * @author
 */
@Service
public class TaskServiceImpl implements TaskService {

    private static final Logger logger = LoggerFactory.getLogger(TaskServiceImpl.class);

    @Autowired
    private TaskDao taskDao;

    @Autowired
    private RuleInstDao ruleInstDao;

    @Autowired
    private TaskProduceLogDao taskProduceLogDao;

    @Autowired
    private TaskExecDao taskExecDao;

    @Autowired
    private AcctDao acctDao;

    @Autowired
    private TaskStatMao taskStatMao;

    @Autowired
    private TaskViewTimeDao taskViewTimeDao;

    @Autowired
    private AcctLogEao acctLogEao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private VideoViewStatMao videoViewStatMao;

    @Autowired
    private EventClient eventClient;

    @Autowired
    private DailyTaskMao dailyTaskMao;

    @Autowired
    private TaskViewAdvertDao taskViewAdvertDao;

    @Autowired
    private AdNumPriceDao adNumPriceDao;

    @Autowired
    private TurntableNumPriceDao turntableNumPriceDao;

    //每日任务
    private static final int DailyTasks = 300; //单位秒

    @Value("${task.limitDate:2021-01-21 00:00:00}")
    private String limitDateStr;

    @Autowired
    private UserTreeDao userTreeDao;

    @Value("${task.teamDate:2021-02-05 00:00:00}")
    private String taskTeamDate;

    @Override
    public Page<Task> taskList(Long userId, int pageNumber, int pageSize) {
        return taskDao.taskList(userId, pageNumber, pageSize);
    }

    @Override
    public Page<Task> oldTask(Long userId, int pageNumber, int pageSize) {
        return taskDao.oldList(userId, RuleInst.STATUS_TO_COMPLETE, pageNumber, pageSize);
    }

    @Override
    public CollecTaskVo collecTask(Long userId, Long taskId, String pwd) {
        //判断该用户是否已获取任务
        CollecTaskVo vo = new CollecTaskVo();
        Task task = taskDao.getTask(taskId);
        if (task == null) {
            vo.setCode("1109");
            vo.setMessage("任务有误，请检查");
            return vo;
        }

        User user = userDao.getById(userId);

        if (!user.getFaceAuth().equals("1")) {
            vo.setCode("1104");
            vo.setMessage("您还未实名");
            return vo;
        }

        //如果是团队任务，判断必须满足团体人数是否满足
        if (Task.TASK_TYPE_RECOMM_TEAM.equals(task.getTaskType())){
            Integer teamNum = userTreeDao.countTaskTeamNum(userId, TimeUtil.parse(taskTeamDate, TimeUtil.FORMAT_YYYYMMDDHHMMSS));
            if (null == task.getTeamNum() || teamNum < task.getTeamNum()){
                vo.setCode("2010");
                vo.setMessage("您的团队人数不满足，兑换任务失败！");
                return vo;
            }
        } else {
            //注册老用户不能领取任务
            Date limitDate = TimeUtil.parse(this.limitDateStr, "yyyy-MM-dd HH:mm:ss");
            if (null != limitDate && null != user.getCreateTime() && user.getCreateTime().before(limitDate)) {
                vo.setCode("1119");
                vo.setMessage("您不能兑换任务！");
                return vo;
            }
        }

        Integer rule = ruleInstDao.getRuleInst(userId, taskId);

        //不需要用果子兑换的就不用校验密码
        if (task.getPrice().compareTo(new BigDecimal(0)) == 1) {
            if (StringUtil.isEmpty(user.getTradePwd())) {
                vo.setCode("1101");
                vo.setMessage("您还未设置交易密码");
                return vo;
            }
            if (StringUtil.isEmpty(pwd)) {
                vo.setCode("1102");
                vo.setMessage("请输入密码");
                return vo;
            }
            if (!AesUtil.encode(pwd).equals(user.getTradePwd())) {
                vo.setCode("1103");
                vo.setMessage("交易密码错误");
                return vo;
            }
        }

        if (task.getLimitNum() <= rule) {
            vo.setCode("1105");
            vo.setMessage("当前任务该用户已领取");
            return vo;
        }
        //判断用户果币是否足够
        Acct acct = acctDao.queryAcctByUIdAndType(userId, AcctType.ACCT_TYPE_G);
        if (acct == null) {
            vo.setCode("1106");
            vo.setMessage("您还未开通账户");
            return vo;
        }
        if (StringUtil.isNotEmpty(task.getPrice().toString())) {
            if ((task.getPrice().compareTo(acct.getBalanceFee())) == 1) {//price 大于 balanceFee 苹果数大于账户余额
                vo.setCode("1107");
                vo.setMessage("您的余额不足");
                return vo;
            }
        }
        Db.tx(() -> {
            Boolean isTask = false; //是否是今日任务
            RuleInst ruleInst = new RuleInst();
            ruleInst.setUserId(userId);
            ruleInst.setTaskId(task.getTaskId());
            ruleInst.setCreateTime(new Date());
            //判断用户今天是否有任务,有任务生效时间推迟到第二天零点
            RuleInst userTask = ruleInstDao.getDayTask(userId);
            Calendar ca = Calendar.getInstance();
            if (userTask != null) {
                //获取明天零点时间
                ca.add(Calendar.DATE, 1);
                Date time = ca.getTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");//注意月份是MM
                try {
                    ruleInst.setEffDate(simpleDateFormat.parse(simpleDateFormat.format(time)));
                    ca.setTime(time);
                    ca.add(Calendar.DATE, task.getProduceDay() + 1);
                    ruleInst.setExpDate(simpleDateFormat.parse(simpleDateFormat.format(ca.getTime())));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {
                //没有任务拿当前时间
                ruleInst.setEffDate(ruleInst.getCreateTime());
                //结束时间
                ca.setTime(ruleInst.getCreateTime());
                ca.add(Calendar.DATE, task.getProduceDay());
                ruleInst.setExpDate(ca.getTime());
                isTask = true;

            }
            ruleInst.setAllValue(task.getAllValue());
            //剩余产值
            ruleInst.setSurplusValue(task.getAllValue());

            ruleInst.setStatus(ruleInst.STATUS_ONGOING);
            ruleInst.setAllDay(0);
            //每日释放值
            //天数转BigDecimal
            BigDecimal b = new BigDecimal(task.getProduceDay());
            BigDecimal divide = task.getAllValue().divide(b, 3, BigDecimal.ROUND_DOWN);
            //每天完成任务的平安果
            ruleInst.setDayValue(divide);
            Long save = ruleInstDao.save(ruleInst);
            if (isTask) {
                //清空mongo(第一个任务之前今天的广告不算)
                TaskStatMo taskStatMo = taskStatMao.findByUserId(userId);
                if (taskStatMo != null) {
                    taskStatMo.setViewDayTime(0);
                    taskStatMo.setInstId(save);
                    taskStatMo.setTaskTime(task.getTaskTime().longValue());
                    //设置状态为有任务
                    taskStatMo.setDayTaskFlag("1");
                    taskStatMao.update(taskStatMo);
                }
            }
            //任务添加成功 账户扣掉任务果币
            if (task.getPrice().compareTo(new BigDecimal(0)) == 1) {
                //值存入用户账号
                acctDao.minusBalance(userId, "G", task.getPrice(), save.toString(),
                        AcctTradeType.EXCHANGE_REDUCE, BusiType.EXCHANGE_CODE);

                acctLogEao.save(UuidUtil.get(), acct.getAcctId(), userId, AcctType.ACCT_TYPE_G, task.getPrice(),
                        Acct.FEE_IN_DE_MINUS, save.toString(), AcctTradeType.EXCHANGE_REDUCE, AcctTradeType.EXCHANGE_REDUCE_NAME,
                        BusiType.EXCHANGE_CODE, new Date());
            }
            //约定1108是成功
            vo.setCode("1108");
            vo.setMessage("任务领取成功");
            return true;
        });
        return vo;
    }


    @Override
    public Page<RuleInst> myTaskList(Long userId, int pageNumber, int pageSize) {
        Page<RuleInst> ruleInsts = ruleInstDao.myTaskList(userId, RuleInst.STATUS_ONGOING, pageNumber, pageSize);
        return ruleInsts;
    }

    @Override
    public Page<RuleInst> myTaskRecord(Long userId, int pageNumber, int pageSize) {
        Page<RuleInst> ruleInsts = ruleInstDao.listDayRuleInst(userId, RuleInst.STATUS_ONGOING, pageNumber, pageSize);
        return ruleInsts;
    }

    //时间改成条
    @Override
    public String todayProgress(Long userId) {
        //获取用户今日任务时长
        RuleInst userTotalTiem = ruleInstDao.getUserTotalTiem(userId);
        //获取mongodb该用户今日视频观看
        TaskStatMo taskStatMo = taskStatMao.findByUserId(userId);

        //int dayTaskNum = 3;
        int todayTaskNum = 0;
        if (null != userTotalTiem){
            todayTaskNum = Integer.valueOf(userTotalTiem.getTotalTiem());
        }
        //int totalTaskNum = dayTaskNum + todayTaskNum;
        int totalTaskNum = todayTaskNum;

        //int dayFinishTaskNum = sumFinishDailyTask(userId);
        int todayFinishTaskNum = 0;

        if (null != taskStatMo && taskStatMo.getViewDay().equals(DateUtil.getDate())){
            if (taskStatMo.getViewDayTime() >= todayTaskNum){
                todayFinishTaskNum = todayTaskNum;
            } else {
                todayFinishTaskNum = taskStatMo.getViewDayTime();
            }
        }

//        int totalFinishTaskNum = dayFinishTaskNum + todayFinishTaskNum;
        int totalFinishTaskNum = todayFinishTaskNum;

        //总完成为0，返回0； 总需要完成为0，也返回0
        if (totalFinishTaskNum == 0 || totalTaskNum == 0){
            return "0";
        }

        BigDecimal percentage = new BigDecimal(totalFinishTaskNum).divide(new BigDecimal(totalTaskNum), 2, BigDecimal.ROUND_HALF_EVEN);
        percentage = percentage.multiply(new BigDecimal(100));
        return percentage.toString();

    }

    public Integer sumFinishDailyTask(Long userId) {
        DailyTaskMo dailyTaskMo = dailyTaskMao.findByUserId(userId);
        String today = DateUtil.getDate();

        if (null == dailyTaskMo) {
            return 0;
        }
        if (!today.equals(dailyTaskMo.getViewDay())) {
            return 0;
        }
        int num = 0;

        if ("1".equals(dailyTaskMo.getAdOne())) {
            num++;
        }
        if ("1".equals(dailyTaskMo.getAdTwo())) {
            num++;
        }
        if ("1".equals(dailyTaskMo.getAdThree())) {
            num++;
        }

        return num;
    }

    /**
     * 一键结算
     *
     * @return void
     * @Param [userId]
     **/
    @Override
    public void settlement(Long userId) {
        DailyTaskMo mo = dailyTaskMao.findByUserId(userId);
        if (null == mo || !(mo.getViewDay().equals(DateUtil.formatDate(new Date())) && "1".equals(mo.getStatus()))) {
            BizUtil.exception("请完成每日任务[观看三条广告], 再进行结算。");
        }
        //获取2天内未结算的平安果
        List<TaskExec> list = taskExecDao.list(userId, TaskExec.STATUS_UNSETTLED);
        if (list.size() == 0) {
            BizUtil.exception("您当前没有可以结算的任务");
        }
        Db.tx(() -> {
            BigDecimal sum = new BigDecimal(0);
            Long instId = null;
            for (TaskExec t : list) {
                sum = sum.add(t.getDayValue());
                instId = t.getInstId();

            }
            if (!BigDecimalUtl.isGreaterThanZero(sum)) {
                BizUtil.exception(ERROR_ACCT_DATA_CHANGE);
            }

            //添加任务产出日志
            Long produceLog = saveTaskProduceLog(userId, instId, sum);
            //值存入用户账号
            acctDao.addBalance(userId, "G", sum, produceLog.toString(), AcctTradeType.INCREASE_IN_TRANSACTIONS, BusiType.PINGAN_FRUIT_CODE);
            for (TaskExec t : list) {
                //修改任务执行日志状态 为以结算
                taskExecDao.updateStatus(userId, t.getExecId(), TaskExec.STATUS_SETTLED);
            }
            //记录es日志
            Acct acct = acctDao.queryAcctByUIdAndType(userId, AcctType.ACCT_TYPE_G);
            acctLogEao.save(UuidUtil.get(), acct.getAcctId(), userId, AcctType.ACCT_TYPE_G, sum,
                    Acct.FEE_IN_DE_ADD, produceLog.toString(), AcctTradeType.SETTLEMENT_ADD, AcctTradeType.SETTLEMENT_ADD_NAME,
                    BusiType.PINGAN_FRUIT_CODE, new Date());

            return true;
        });
    }

    @Override
    public String unsettledValue(Long userId) {
        //获取2天内未结算的平安果
        List<TaskExec> list = taskExecDao.list(userId, TaskExec.STATUS_UNSETTLED);
        BigDecimal sum = new BigDecimal(0);
        for (TaskExec t : list) {
            sum = sum.add(t.getDayValue());
            System.out.println(sum);
        }
        return sum.toString();
    }

    @Override
    public Page<TaskExec> listTaskExec(Long userId, String status, int pageNumber, int pageSize) {
        Page<TaskExec> taskExecPage = taskExecDao.listTaskExec(userId, status, pageNumber, pageSize);
        return taskExecPage;
    }

    @Override
    public String dailyTasks(Long userId) {
        //根据用户id 取mongo 用户观看视频数
        //获取mongodb该用户今日视频观看时长
        VideoViewStatMo videoViewStatMo = videoViewStatMao.findByUserId(userId);
        if (videoViewStatMo != null) {
            if (videoViewStatMo.getViewDay().equals(DateUtil.formatDate(new Date())) && videoViewStatMo.getViewDayTime() >= this.DailyTasks) {
                return "完成";
            } else {
                return "未完成";
            }
        } else {
            return "未完成";
        }
    }

    @Override
    public TaskExec getTaskExec(Long userId, Long instId) {
        return taskExecDao.getTaskExec(userId, instId);
    }

    @Override
    public Integer getTaskStatMo(Long userId) {
        TaskStatMo mo = taskStatMao.findByUserId(userId);
        if (mo != null) {
            if (mo.getViewDay().equals(DateUtil.getDate())) {
                return mo.getViewDayTime();
            }
        }
        return 0;
    }

    //timeLong 改成次数 前端点一次加1
    @Override
    public void addVideoCount(Long userId, String advertId) {
        TaskStatMo taskStatMo = taskStatMao.findByUserId(userId);
        int timeLong = 1;
        String viewDay = DateUtil.formatDate(new Date());
        if (null == taskStatMo) {
            taskStatMo = newDayMo(userId, viewDay, timeLong);
            taskStatMo.setViewTotalTime(1);
            taskStatMao.save(taskStatMo);
        } else {
            String viewDayMo = taskStatMo.getViewDay();
            //如果存的是同一天
            if (viewDay.equals(viewDayMo)) {
                if (taskStatMo.getDayTaskFlag().equals("1")) {
                    //有任务则去处理任务
                    handleTask(userId, taskStatMo, timeLong);
                } else {
                    //没有任务更新每日看视频时长
                    taskStatMo.setViewDayTime(taskStatMo.getViewDayTime() + timeLong);
                    taskStatMo.setViewTotalTime(taskStatMo.getViewTotalTime() + timeLong);
                    taskStatMao.update(taskStatMo);
                }
            } else {
                //todo 插入每日看视频的历史数据
                taskViewTimeDao.save(taskStatMo.getUserId(), taskStatMo.getViewDay(), taskStatMo.getViewDayTime());

                TaskStatMo newtaskStatMo = newDayMo(userId, viewDay, timeLong);
                newtaskStatMo.setViewTotalTime(taskStatMo.getViewTotalTime() + timeLong);
                taskStatMao.update(newtaskStatMo);
            }
        }
    }

    @Override
    public Integer myClaim(Long userId, Long taskId) {
        return ruleInstDao.myClaim(userId, taskId);
    }


    /**
     * 添加任务产出日志
     *
     * @return java.lang.Long
     * @Param [ruleInst]
     **/
    private Long saveTaskProduceLog(Long userId, Long InstId, BigDecimal dayValue) {
        TaskProduceLog taskProduceLog = new TaskProduceLog();
        taskProduceLog.setUserId(userId);
        taskProduceLog.setInstId(InstId);
        taskProduceLog.setProduceNum(dayValue);
        taskProduceLog.setCreateTime(new Date());
        return taskProduceLogDao.save(taskProduceLog);
    }


    /**
     * 新的一天
     *
     * @param userId
     * @param viewDay
     * @param timeLong
     * @return
     */
    private TaskStatMo newDayMo(Long userId, String viewDay, Integer timeLong) {
        TaskStatMo taskStatMo = new TaskStatMo();
        taskStatMo.setUserId(userId);
        taskStatMo.setViewDay(viewDay);
        taskStatMo.setViewDayTime(timeLong);
        List<RuleInst> ruleInsts = ruleInstDao.listValidRuleInst(userId);
        List<Long> instIds = getInstIds(ruleInsts);
        List<Long> taskTimes = getLimitNums(ruleInsts);
        if (null != instIds && instIds.size() > 0) {
            taskStatMo.setDayTaskFlag("1");
            taskStatMo.setViewTaskTime(timeLong);
            //任务标识
            taskStatMo.setInstId(instIds.get(0));
            instIds.remove(0);
            taskStatMo.setInstIds(instIds);
            //任务条件
            taskStatMo.setTaskTime(taskTimes.get(0));
            taskTimes.remove(0);
            taskStatMo.setTaskTimes(taskTimes);
        } else {
            taskStatMo.setDayTaskFlag("0");
            taskStatMo.setViewTaskTime(0);
            taskStatMo.setInstIds(new ArrayList<>());
        }

        return taskStatMo;
    }

    private List<Long> getInstIds(List<RuleInst> ruleInsts) {
        List<Long> instIds = new ArrayList<>();
        if (null == ruleInsts || ruleInsts.isEmpty()) {
            return null;
        }
        for (RuleInst ruleInst : ruleInsts) {
            instIds.add(ruleInst.getInstId());
        }
        return instIds;
    }

    private List<Long> getLimitNums(List<RuleInst> ruleInsts) {
        List<Long> taskTimes = new ArrayList<>();
        if (null == ruleInsts || ruleInsts.isEmpty()) {
            return null;
        }
        for (RuleInst r : ruleInsts) {
            taskTimes.add(r.getLong("task_time"));
        }
        return taskTimes;
    }


    private void handleTask(Long userId, TaskStatMo taskStatMo, Integer timeLong) {
        Integer viewTaskTime = taskStatMo.getViewTaskTime() + timeLong;

        taskStatMo.setViewDayTime(taskStatMo.getViewDayTime() + timeLong);
        taskStatMo.setViewTaskTime(taskStatMo.getViewTaskTime() + timeLong);
        taskStatMo.setViewTotalTime(taskStatMo.getViewTotalTime() + timeLong);

        //如果大于设置的条数
        if (viewTaskTime >= taskStatMo.getTaskTime()) {
            //处理完成任务
            toFinishTask(taskStatMo);

            taskStatMo.setViewTaskTime(0);
            List<Long> instIds = taskStatMo.getInstIds();
            List<Long> taskTimes = taskStatMo.getTaskTimes();
            if (null != instIds && instIds.size() > 0 && null != taskTimes && taskTimes.size() > 0) {
                //任务标识
                taskStatMo.setInstId(instIds.get(0));
                instIds.remove(0);
                taskStatMo.setInstIds(instIds);
                //任务条件
                taskStatMo.setTaskTime(taskTimes.get(0));
                taskTimes.remove(0);
                //taskStatMo.setInstIds(taskTimes);
            } else {
                taskStatMo.setInstId(0L);
                //如果没有任务了，则更新为没有任务的标识
                taskStatMo.setDayTaskFlag("0");
            }
        }
        taskStatMao.update(taskStatMo);
    }

    private void toFinishTask(TaskStatMo taskStatMo) {
        TaskExec dayTaskExec = taskExecDao.getByCond(taskStatMo.getUserId(), taskStatMo.getViewDay(), taskStatMo.getInstId());
        //如果当日任务已经执行了，则不做处理
        if (null != dayTaskExec) {
            return;
        }

        Db.tx(() -> {
            RuleInst ruleInst = ruleInstDao.getById(taskStatMo.getInstId());
            if (ruleInst == null) {

            }
            BigDecimal surplusValue = ruleInst.getSurplusValue();
            BigDecimal dayValue = ruleInst.getDayValue();
            if (surplusValue.compareTo(dayValue) < 0) {
                dayValue = surplusValue;
                surplusValue = BigDecimal.ZERO;
                ruleInst.setStatus(RuleInst.STATUS_TO_COMPLETE);
            } else {
                surplusValue = surplusValue.subtract(dayValue);
            }
            ruleInst.setSurplusValue(surplusValue);
            ruleInstDao.update(ruleInst);

            TaskExec taskExec = new TaskExec();
            taskExec.setInstId(taskStatMo.getInstId());
            taskExec.setDayTime(taskStatMo.getViewDay());
            taskExec.setDayValue(dayValue);
            taskExec.setCreateTime(new Date());
            taskExec.setStatus(TaskExec.STATUS_UNSETTLED);
            taskExec.setUserId(taskStatMo.getUserId());
            taskExecDao.save(taskExec);

            return true;
        });
    }

    /**
     * 记录观看视频时间
     *
     * @return void
     * @Param [videoViewStatMo, time, viewDay]
     **/
    public void newVideoDay(Integer time, Long userId) {
        Map<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        //param.put("videoId", videoId);
        param.put("timeLong", time);
        eventClient.fireEvent(Const.EVENT_TOPIC_VIEW_VIDEO_TIME, JSON.toJSONString(param));
        String viewDay = DateUtil.formatDate(new Date());
        VideoViewStatMo videoViewStatMo = videoViewStatMao.findByUserId(userId);
        VideoViewStatMo vi = new VideoViewStatMo();
        vi.setUserId(userId);
        //不同新建
        if (videoViewStatMo == null) {
            vi.setViewDayTime(time);
            vi.setViewDay(viewDay);
            vi.setViewTotalTime(time);
            videoViewStatMao.save(vi);
        } else {
            if (viewDay.equals(videoViewStatMo.getViewDay())) { //日期相同相加
                vi.setViewDay(viewDay);
                vi.setViewDayTime(videoViewStatMo.getViewDayTime() + time);
                vi.setViewTotalTime(videoViewStatMo.getViewTotalTime() + time);
                vi.setViewDay(viewDay);
                videoViewStatMao.update(vi);
            } else {
                vi.setViewDayTime(time);
                vi.setViewDay(viewDay);
                vi.setViewTotalTime(videoViewStatMo.getViewTotalTime() + time);
                videoViewStatMao.update(vi);
            }
        }
    }

    /**
     * 1设置交易密码 2未交易密码
     *
     * @return java.lang.String
     * @Param [userId]
     **/
    public String userTransactionPwd(Long userId) {
        User user = userDao.getById(userId);
        if (StringUtil.isEmpty(user.getTradePwd())) {
            return "2";
        }
        return "1";
    }

    @Override
    public void viewDailyTask(Long userId, String advert) {
        DailyTaskMo mo = dailyTaskMao.findByUserId(userId);
        String viewDay = DateUtil.formatDate(new Date());
        if (null == mo) { //没有新建
            mo = newDailyTaskMo(userId, advert, viewDay);
            dailyTaskMao.save(mo);
        } else {//有修改
            //如果存的不是同一天 更新时间
            String viewDayMo = mo.getViewDay();
            if (!viewDay.equals(viewDayMo)) {
                //记录下日志
                try {
                    taskViewAdvertDao.save(mo.getUserId(), mo.getAdOne(), mo.getAdTwo(), mo.getAdThree(), mo.getViewDay(), mo.getStatus());
                } catch (Exception e) {
                    logger.error("", e);
                }

                mo.setViewDay(viewDay);
                mo.setStatus("0");
                mo.setAdOne("0");
                mo.setAdTwo("0");
                mo.setAdThree("0");
            }
            updateDailyTaskMo(mo, advert);
            dailyTaskMao.update(mo);
        }
    }

    @Override
    public OnDayTaskVo onDayTask(Long userId) {
        //根据用户id 取mongo 用户观看视频数
        //获取mongodb该用户今日视频观看时长
        OnDayTaskVo vo = new OnDayTaskVo();
        DailyTaskMo mo = dailyTaskMao.findByUserId(userId);
        String viewDay = DateUtil.formatDate(new Date());
        if (null == mo || !viewDay.equals(mo.getViewDay())) {
            vo.setStatus("0");
            vo.setUserId(userId);
            vo.setAdTwo("0");
            vo.setAdThree("0");
            vo.setAdOne("0");
        } else {
            vo.setStatus(mo.getStatus());
            vo.setUserId(mo.getUserId());
            if (mo.getStatus().equals("1")) {
                vo.setAdTwo("1");
                vo.setAdThree("1");
                vo.setAdOne("1");
            } else {
                vo.setAdTwo(mo.getAdTwo() == null ? "0" : mo.getAdTwo());
                vo.setAdThree(mo.getAdThree() == null ? "0" : mo.getAdThree());
                vo.setAdOne(mo.getAdOne() == null ? "0" : mo.getAdOne());
            }
        }
        return vo;
    }

    @Override
    public List<AdNumPrice> listAdNumPrice() {
        return adNumPriceDao.list();
    }

    @Override
    public List<TurntableNumPrice> listTurntableNumPrice() {
        return turntableNumPriceDao.list();
    }

    private void updateDailyTaskMo(DailyTaskMo mo, String advert) {
        advert(mo, advert);
        //完成
        if ("1".equals(mo.getAdOne()) && "1".equals(mo.getAdThree()) && "1".equals(mo.getAdTwo())) {
            mo.setStatus("1");
        }
    }

    //第一次没有新建
    private DailyTaskMo newDailyTaskMo(Long userId, String advert, String viewDay) {
        DailyTaskMo mo = new DailyTaskMo();
        mo.setUserId(userId);
        mo.setStatus("0");
        mo.setAdOne("0");
        mo.setAdTwo("0");
        mo.setAdThree("0");
        mo.setViewDay(viewDay);
        advert(mo, advert);
        return mo;
    }

    //广告类型判断
    private void advert(DailyTaskMo mo, String advert) {
        if ("PEGASUS_ADVERT".equals(advert)) {
            mo.setAdOne("1");
        } else if ("PLATFORM_ADVERT".equals(advert)) {
            mo.setAdTwo("1");
        } else if ("BAMBOO_SLIPS_ADVERT".equals(advert)) {
            mo.setAdThree("1");
        }
    }
}
